package ch.sv7.tool.dbmanager.db.fixbuilder;

import java.util.ArrayList;
import java.util.List;

import ch.sv7.tool.dbmanager.Context;
import ch.sv7.tool.dbmanager.db.ForeignKeySchema;
import ch.sv7.tool.dbmanager.db.TableSchema;
import ch.sv7.tool.dbmanager.db.dialect.Dialect;
import ch.sv7.tool.dbmanager.db.difference.ExtraTableDifference;
import ch.sv7.tool.dbmanager.db.difference.SchemaDifference;
import ch.sv7.tool.dbmanager.db.fix.DropForeignKeyFix;
import ch.sv7.tool.dbmanager.db.fix.DropTableFix;
import ch.sv7.tool.dbmanager.db.fix.SchemaFix;

/**
 * Process an extra table scenario.
 * This is an extremely dangerous action. This is why
 * you need to set an extra parameter to activate it. 
 *
 * @author svt
 *
 */
public class ExtraTableFixBuilder implements FixBuilder {

	public SchemaFix[] createFixes(SchemaDifference difference, Dialect dialect, Context context) {
		ExtraTableDifference extraTableDifference = (ExtraTableDifference)difference;
		if (context.doDropExtraTable()){
			TableSchema ts = extraTableDifference.getActualTableSchema();
			List fixes = new ArrayList();
			SchemaFix dropTableFix = new DropTableFix(ts);
			fixes.add(dropTableFix);
			List fks = ts.getReferencedForeignKeys();
			for (int i=0; i<fks.size(); i++) {
				ForeignKeySchema fk = (ForeignKeySchema)fks.get(i);
				if (fk.getForeignTable().equals(ts.getName())){
					DropForeignKeyFix dropFK = new DropForeignKeyFix(fk);
					fixes.add(dropFK);
				}
			}
			return (SchemaFix[])fixes.toArray(new SchemaFix[fixes.size()]);
		} else {
			return new SchemaFix[0];
		}
	}

}
